package com.zhentao.PollutionPredictio.model.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhentao.PollutionPredictio.model.mapper.PollutionAnalysisRecordMapper;
import com.zhentao.PollutionPredictio.model.service.IPollutionAnalysisRecordService;
import com.zhentao.pojo.PollutionAnalysisRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 污染分析记录服务实现类
 */
@Service
public class PollutionAnalysisRecordServiceImpl extends ServiceImpl<PollutionAnalysisRecordMapper, PollutionAnalysisRecord> 
        implements IPollutionAnalysisRecordService {

    @Autowired
    private PollutionAnalysisRecordMapper pollutionAnalysisRecordMapper;

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public PollutionAnalysisRecord saveAnalysisRecord(Long factoryId, String factoryName, 
                                                    String analysisType, String analysisResult, 
                                                    String inputParameters, String weatherData, String poiData) {
        try {
            PollutionAnalysisRecord record = new PollutionAnalysisRecord();
            record.setFactoryId(factoryId);
            record.setFactoryName(factoryName);
            record.setAnalysisType(analysisType);
            record.setAnalysisResult(analysisResult);
            record.setInputParameters(inputParameters);
            record.setWeatherData(weatherData);
            record.setPoiData(poiData);
            record.setAnalysisTime(LocalDateTime.now());
            record.setCreateTime(LocalDateTime.now());
            record.setUpdateTime(LocalDateTime.now());
            record.setStatus(1);
            record.setRemark("AI自动分析生成");

            this.save(record);
            return record;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("保存分析记录失败: " + e.getMessage());
        }
    }

    @Override
    public List<PollutionAnalysisRecord> getAnalysisHistory(Long factoryId) {
        return pollutionAnalysisRecordMapper.selectByFactoryId(factoryId);
    }

    @Override
    public List<PollutionAnalysisRecord> getRecentAnalysis(Long factoryId, Integer limit) {
        return pollutionAnalysisRecordMapper.selectRecentRecords(factoryId, limit);
    }
}
